package com.web.estate.common;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;

public class UrlBroker {
	private String url;

	private Map<String, String> queryData = new HashMap<String, String>();

	private String reference;

	public UrlBroker(String url) {
		this.url = url;
	}

	public UrlBroker addQueryData(String key, String value) {
		if (StringUtils.isBlank(key) || StringUtils.isBlank(value)) {
			return this;
		}
		queryData.put(key, value);
		return this;
	}

	public UrlBroker removeQueryData(String key) {
		queryData.remove(key);
		return this;
	}

	public UrlBroker clearQueryData() {
		queryData.clear();
		return this;
	}

	public UrlBroker setReference(String reference) {
		this.reference = reference;
		return this;
	}

	public UrlBroker clearReference() {
		this.reference = null;
		return this;
	}

	public String fork() {
		StringBuilder builder = new StringBuilder();
		builder.append(url);

		Iterator<Entry<String, String>> it = queryData.entrySet().iterator();
		if (!queryData.isEmpty()) {
			builder.append("?");
		}

		while (it.hasNext()) {
			Entry<String, String> next = it.next();
			try {
				builder.append(URLEncoder.encode(next.getKey(), "utf-8")).append("=").append(
						URLEncoder.encode(next.getValue(), "utf-8"));
			} catch (UnsupportedEncodingException e) {
				throw new RuntimeException(e);
			}

			if (it.hasNext()) {
				builder.append("&");
			}
		}

		if (reference != null) {
			builder.append("#").append(reference);
		}
		return builder.toString();
	}

}
